package com.changguo.file.controller;


import com.changgou.entity.Result;
import com.changguo.file.util.FastDFSClient;
import com.changguo.file.util.FastDFSFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("file")
public class FileController {

    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) {


        try {
            //文件的名称
            String filename = file.getOriginalFilename();
            //文件的内容
            byte[] content = file.getBytes();
            //获取文件的扩展名 从文件的名称截取
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            System.out.println("文件扩展名： " + ext);

            // 文件名称 ， 文件内容    文件扩展名
            FastDFSFile fastDFSFile = new FastDFSFile(filename, content, ext);
            String[] uploadResults = FastDFSClient.upload(fastDFSFile);

            //获取组名
            String groupName = uploadResults[0];
            //获取文件存储路径
            String remoteFileName = uploadResults[1];
            String fileUrl = FastDFSClient.getTrackerUrl() + groupName + "/" + remoteFileName;
            System.out.println("文件上传成功后的路径： " + fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  new Result();
    }
}
